package com.geezdata.cps.base.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ContextUtil implements ApplicationContextAware {
	private static ApplicationContext applicationContext = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {	
		ContextUtil.applicationContext = applicationContext;
	}
	
	public static ApplicationContext getApplicationContext() {
		return ContextUtil.applicationContext;
	}
	
	public static <T> T getBean(Class<T> type) throws BeansException {
		return applicationContext.getBean(type);
	}
	
	public static <T> List<T> getBeansOfType(Class<T> type) {
		Map<String, T> beanMap = applicationContext.getBeansOfType(type);
		if(beanMap == null) {
			return null;
		}
		
		List<T> beanList = new ArrayList<T>(beanMap.size());
		for(Entry<String, T> entry : beanMap.entrySet()) {
			beanList.add(entry.getValue());
        }
        return beanList;
	}
}
